/* 微信分享，授权 */
import axios from 'axios'
import qs from 'qs'
import {randomString} from '@/utils'
import store from '@/store'

const sha1 = require('sha1')
const wx = require('weixin-js-sdk')

// 分享
function wxShare ({appMessage, timeLine}) {
  axios.get('http://www.eqask.com/Home/index.php/WxApi/getsign?public_id=6I1A4ZL8')
    .then(res => {
      let data = res.data
      if (data) {
        let timestamp = Date.parse(new Date())
        let jsapiTicket = data.jsapi_ticket
        let url = window.location.href
        if (window.wxURL) {
          url = window.wxURL
        }
        let nonceStr = randomString()
        let appId = data.appId
        let string1 = 'jsapi_ticket=' + jsapiTicket + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + url
        let signature = sha1(string1)
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appId, // 必填，公众号的唯一标识
          timestamp: timestamp, // 必填，生成签名的时间戳
          nonceStr: nonceStr, // 必填，生成签名的随机串
          signature: signature, // 必填，签名，见附录1
          jsApiList: [
            'onMenuShareTimeline', 'onMenuShareAppMessage'
          ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        })
        wx.ready(function () {
          wx.onMenuShareTimeline(timeLine)
          wx.onMenuShareAppMessage(appMessage)
        })
      }
    })
}

// 授权
function wxAuth (code) {
  // http://sae.wecozhiku.com/admin/login/CodeToOpenid
  axios.post('http://sae.wecozhiku.com/admin/Wxapiaction/CodeToOpenid', qs.stringify({code}), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
    .then(res => {
      // alert(JSON.stringify(res))
      if (res.data.status === 1) {
        let user = JSON.parse(res.data.data)
        store.commit('SET_AVATAR', user.headimgurl)
        localStorage.setItem('userInfo', res.data.data)
        location.href = location.href.split('code=')[0]
      }
    })
}

export {
  wxShare,
  wxAuth
}
